<template>
  <div>
    <el-container>
      <el-header class="bb">

        <el-row>
          <el-col :span="2">
            <img src="@/assets/img/logo.png" width="150px" height="60px" @click="$router.push('/home')" />
          </el-col>
          <el-col :span="2" :offset="9">
            <h1><i class="el-icon-edit"></i>写文章</h1>
          </el-col>
          <el-col :span="2" :offset="9">
            <el-button type="primary" v-if="!isUpdate" round @click="submitForm('ruleForm')" >发布博客</el-button>
            <el-button type="primary" v-else round @click="submitUpdateForm('ruleForm')" >更新博客</el-button>
            <!-- <el-menu
              :default-active="activeIndex"
              class="el-menu-demo"
              mode="horizontal"
              @select="handleSelect"
            >
              <el-submenu index="1">
                <template slot="title"> >发布文章 </template>
                <el-menu-item index="1-1">选项1</el-menu-item>
                <el-menu-item index="1-2">选项2</el-menu-item>
                <el-menu-item index="1-3">选项3</el-menu-item>
                <el-submenu index="1-4">
                  <template slot="title">选项4</template>
                  <el-menu-item index="1-4-1">选项1</el-menu-item>
                  <el-menu-item index="1-4-2">选项2</el-menu-item>
                  <el-menu-item index="1-4-3">选项3</el-menu-item>
                </el-submenu>
              </el-submenu>
            </el-menu> -->
          </el-col>
          
        </el-row>



      </el-header>

      <el-main>



        <el-form ref="ruleForm" :model="article" :rules="rules">
          <el-form-item label-width="0" prop="title">
            <el-input
              type="textarea"
              v-model="article.title"
              :rows="4"
              
              placeholder="请输入文章标题"
            ></el-input>
          </el-form-item>

          <el-form-item label-width="0" prop="content">
            <mavon-editor ref="md" @imgAdd="imgAdd" v-model="article.content" :toolbars="toolbars" class="content" />
           
          </el-form-item>

          <el-form-item class="item">
            <el-form-item label="文章标签：">
              <el-checkbox-group v-model="tagName">
                <el-checkbox v-for="item in tag" :key="item.id" :label="item.tagName" name="type" @change="getTagId(item.id)"></el-checkbox>
             
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="文章类型：" prop="sortId">
              <el-radio-group v-model="sortName" >
                <el-radio v-for="item in classify" :key="item.id" :label="item.sortName" @change="getSortId(item.sortName,item.id)"></el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- <el-form-item label="发布形式：">
              <el-radio-group v-model="form.resource">
                <el-radio label="全部可见"></el-radio>
                <el-radio label="仅我可见"></el-radio>
                <el-radio label="粉丝可见"></el-radio>
                <el-radio label="VIP可见"></el-radio>
              </el-radio-group>
            </el-form-item> -->
            <!-- <el-form-item label="内容等级：">
              <el-radio-group v-model="form.resource">
                <el-radio label="初级"></el-radio>
                <el-radio label="中级"></el-radio>
                <el-radio label="高阶"></el-radio>
              </el-radio-group>
            </el-form-item> -->
          </el-form-item>

          <!-- <el-form-item class="item-footer">
            <div  class="item-footer-1">
              <el-button type="primary" round>保存草稿</el-button>
             
              <el-button type="primary" round @click="sendBolg">发布博客</el-button>
            </div>
          </el-form-item> -->
        </el-form>




      </el-main>
    </el-container>
  </div>
</template>

<script>
import {getAllTag} from "@/api/tag"
import {getAllClassify} from '@/api/classify'
import {getUserInfo} from '@/api/user'
import {getToken} from '@/request/token'
import {publish,findArticleById,updateArticle} from '@/api/article'
import {uploadBlog} from '@/api/upload'

export default {
  created(){
 
    getAllTag().then(res=>{
      this.tag=res.data
    }),
    getAllClassify().then(res=>{
      this.classify=res.data
    })
    const token=getToken();
    if(token!=null){
    getUserInfo(token).then(res=>{
      if(!res.success){
        this.$router.push('/home')
      }else{    
        this.article.userId=res.data.id
      }
      
    })
  }
  this.updateId=this.$route.query.id
    if(this.updateId!==undefined){
      this.isUpdate=true
       findArticleById(this.updateId).then(res=>{
        this.article=res.data
       
        this.classify.forEach(v=>{
          // console.log(v.id);
         
          if(this.article.sortId==v.id){
           
            return this.sortName=v.sortName
             
          }
        })

        this.article.tags.forEach(v=>{
          this.tagArr.push(v.id)
          this.tagName.push(v.tagName)
        })
        this.article.tags=[]
        
      })
    }
  },
  data() {
    var checkTitle=(rule,value,callback)=>{
      if(value===''||value===null){
        callback(new Error('标题不能为空！'))
      
    }else{
        callback()
      }
  };
  var checkContent=(rule,value,callback)=>{
      if(value===''||value===null){
        callback(new Error('内容不能为空！'))
      
    }else{
        callback()
      }
  };
  var checkSortId=(rule,value,callback)=>{
      if(value===''||value===null){
        callback(new Error('请选择文章分类！'))
      
    }else{
        callback()
      }
  };
    return {
      updateId:'',
      isUpdate:false,
      sortName:'',
      tagName:[],
      tagArr:[],
      tagForm:{
        id:''
      },
      classify:[],
      tag:[],
      article:{
        userId:'',
        title:'',
        content:'',
        contentHtml:'',
        sortId:'',
        tags:[]
      },
      rules:{
        title:[
          {validator:checkTitle,trigger:'blur'}
        ],
        content:[
          {validator: checkContent,trigger:'blur'}
        ],
        sortId:[
          {validator:checkSortId,trigger:'blur'}
        ]
      },
      activeIndex: "1",
      activeIndex2: "1",
      textarea: "",
      textarea1: "",
       context: ' ',//输入的数据
            toolbars: {
                // bold: true, // 粗体
                // italic: true, // 斜体
                // header: true, // 标题
                // underline: true, // 下划线
                // mark: true, // 标记
                // superscript: true, // 上角标
                // quote: true, // 引用
                // ol: true, // 有序列表
                // link: true, // 链接
                // imagelink: true, // 图片链接
                // help: true, // 帮助
                // code: true, // code
                // subfield: true, // 是否需要分栏
                // fullscreen: true, // 全屏编辑
                // readmodel: true, // 沉浸式阅读
                // undo: true, // 上一步
                // trash: true, // 清空
                // save: true, // 保存（触发events中的save事件）
                // navigation: true, // 导航目录
                bold: true, // 粗体
                italic: true, // 斜体
                header: true, // 标题
                underline: true, // 下划线
                strikethrough: true, // 中划线
                mark: true, // 标记
                superscript: true, // 上角标
                subscript: true, // 下角标
                quote: true, // 引用
                ol: true, // 有序列表
                ul: true, // 无序列表
                link: true, // 链接
                imagelink: true, // 图片链接
                code: true, // code
                table: true, // 表格
                fullscreen: true, // 全屏编辑
                readmodel: true, // 沉浸式阅读
                htmlcode: true, // 展示html源码
                help: true, // 帮助
                /* 1.3.5 */
                undo: true, // 上一步
                redo: true, // 下一步
                trash: true, // 清空
                save: false, // 保存（触发events中的save事件）
                ishljs: false, //代码高亮
                // codeStyle:'agate',
                /* 1.4.2 */
                navigation: true, // 导航目录
                /* 2.1.8 */
                alignleft: true, // 左对齐
                aligncenter: true, // 居中
                alignright: true, // 右对齐
                /* 2.2.1 */
                subfield: true, // 单双栏模式
                preview: true, // 预览

            }
    };
  },
  methods: {
    submitUpdateForm(formName){
      this.$refs[formName].validate((valid) => {
       if (valid) {
        
        // if(this.tagArr.length===0){
        //   return this.$message.warning("请至少选择一个文章标签")
        // }
        this.tagArr.forEach(v=>{
          this.article.tags.push({'id':v})
        })
        this.article.contentHtml=this.converter.makeHtml(this.article.content)
        updateArticle(this.article).then(res=>{
          if(!res.success){
            return this.$message.error("修改失败")
          }
          this.$router.push('/profile')
          return this.$message.success("修改成功")
        })
       } else {
         console.log('error submit!!');
         return false;
       }
     });
    },
    submitForm(formName) {
     
     this.$refs[formName].validate((valid) => {
       if (valid) {
        
        // if(this.tagArr.length===0){
        //   return this.$message.warning("请至少选择一个文章标签")
        // }
        this.tagArr.forEach(v=>{
          this.article.tags.push({'id':v})
        })
        this.article.contentHtml=this.converter.makeHtml(this.article.content)
        console.log(this.article);
        publish(this.article).then(res=>{
          console.log(res);
          if(!res.success){
            return this.$message.error(res.msg)
          }
          this.$router.push('/profile')
          return this.$message.success("发布成功")
        })
       } else {
         console.log('error submit!!');
         return false;
       }
     });
   },
   imgAdd(pos, $file) {
        let formdata = new FormData();
        formdata.append('image', $file);       
        uploadBlog(formdata).then(res => {
          // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)   
          if (res.success) {

            this.$refs.md.$img2Url(pos, res.data+'#pic_center=300x');
          } else {
            console.log();
            this.$message({message: res.msg, type: 'error', showClose: true})
          }

        }).catch(err => {
          this.$message({message: err, type: 'error', showClose: true});
        })
      },
    // handleSelect(key, keyPath) {
    //   console.log(key, keyPath);
    // },
    // sendBolg () {
    //       console.log(this.article);
    //         // console.log(this.context)
    //         // var htmlContent = this.converter.makeHtml(this.context)
    //         // console.log(htmlContent)
    //     },
        getSortId(item,id){
         this.sortName=item
          this.article.sortId=id
        },
        getTagId(id){
        
          if(this.tagArr.indexOf(id)===-1){
            this.tagArr.push(id)
          }else{

            this.tagArr.splice(this.tagArr.indexOf(id),1)
          }
         
        }
  },
  mounted() {
    this.$set(this.article, 'ref', this.$refs.md)
    },
};
</script>

<style scoped lang="less">
.bb {
  position: sticky;
  position: -webkit-sticky;
  top: 0;
  z-index: 999;
}

/deep/.el-submenu__title {
  font-size: 20px;
  font-weight: bold;
}
.el-form {
  padding-left: 200px;
  padding-right: 200px;
}

.el-main {
  background-color: #f2f6fc;
}
.item {
  background-color: white;
  padding: 30px;
  border: 1px solid rgba(59, 58, 58, 0.2);
  
}
.item-footer {
    position: fixed;
    bottom: 0;

}
.content{
  height: 600px;
}
.item-footer-1 {
   
    margin-left: 1500px;
    
}
</style>